package logic

import (
	"Junior_two/subject/cart/cartrpc/pb/cartRpc"
	"context"
	"github.com/astaxie/beego/validation"
	"net/http"

	"Junior_two/subject/cart/cartapi/internal/svc"
	"Junior_two/subject/cart/cartapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type InsertCartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewInsertCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InsertCartLogic {
	return &InsertCartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InsertCartLogic) InsertCart(req *types.Inrequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	valid := validation.Validation{}
	valid.Required(req.UserId, "userId").Message("用户ID不可以为空")
	valid.Required(req.GoodId, "goodId").Message("商品ID不可以为空")
	valid.Required(req.Count, "count").Message("购买数量不可以为空")
	if valid.HasErrors() {
		for _, v := range valid.Errors {
			return &types.Response{
				Msg:  v.Message,
				Code: http.StatusAccepted,
			}, nil
		}
	}
	res, err := l.svcCtx.CartServer.Insert(l.ctx, &cartRpc.InRequest{
		UserId: req.UserId,
		GoodId: req.GoodId,
		Count:  req.Count,
	})
	if err != nil {
		return &types.Response{
			Msg:  err.Error(),
			Code: res.Code,
		}, nil
	}
	if res.Code != http.StatusOK {
		return &types.Response{
			Msg:  res.Msg,
			Code: res.Code,
		}, nil
	}
	return &types.Response{
		Msg:  res.Msg,
		Code: res.Code,
	}, nil
}
